package com.water.camera.activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;

import com.water.camera.adapter.BatchListAdapter;
import com.water.camera.bean.MediaData;
import com.water.camera.databinding.ActivityBatchListBinding;

import java.util.ArrayList;

public class BatchResultPreviewAct extends BaseActivity {

    ActivityBatchListBinding binding;
    BatchListAdapter adapter;
    ArrayList<String> img;
    ArrayList<MediaData> list;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityBatchListBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.ivClose.setOnClickListener(v -> finish());

        img = getIntent().getStringArrayListExtra("output");
        list = getIntent().getParcelableArrayListExtra("img");
        adapter = new BatchListAdapter(this, img);
        binding.vpBatch.setAdapter(adapter);
        binding.vpBatch.setCurrentItem(getIntent().getIntExtra("position", 0));

        binding.btnSave.setOnClickListener(v -> edit());
    }

    private void edit() {
        Intent i = new Intent();
        i.putExtras(getIntent());
        i.putStringArrayListExtra("output", img);
        i.setClass(this, BatchEditAct.class);
        i.putExtra("index", binding.vpBatch.getCurrentItem());
        startActivityForResult(i, 10);
    }

    @Override
    protected boolean paddingTop() {
        return false;
    }

    boolean change = false;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10) {
            if (resultCode == RESULT_OK) {
                change = true;
                int i = data.getIntExtra("index", 0);
                String p = data.getStringExtra("path");
                MediaData tmp = list.get(i);
                tmp.setGlLeftBottomX(data.getFloatExtra("x", 0f));
                tmp.setGlLeftBottomY(data.getFloatExtra("y", 0f));
                tmp.setMark(data.getStringExtra("mark"));
                img.set(i, p);
                adapter.notifyItemChanged(i, p);
            }
        }
    }

    @Override
    public void finish() {
        if (change) {
            Intent i = new Intent();
            i.putStringArrayListExtra("output", img);
            i.putParcelableArrayListExtra("img", list);
            setResult(RESULT_OK, i);
        }
        super.finish();
    }
}
